import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
// 创建axios实例
const service = axios.create({
  // baseURL:基地址
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // 超时的时间
  timeout: 5000 // request timeout
})

// request interceptor  请求拦截器
service.interceptors.request.use(
  config => {
    console.log(config)
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor  响应拦截器
service.interceptors.response.use(

  response => {
    console.log('后端数据', response)
    if (response.data.success === false) {
      return Promise.reject(new Error(response.data.message))
    } else {
      return response.data
    }
  },
  error => {
    console.log('请求出错啦', error)
    if (error.response.data.code === 10002) {
      // token过期
      // 1.删除本地登录信息
      store.dispatch('user/userLogout')
      // 2.跳转 重新登陆
      // router .push( '/login?return_url=' + 当前的path)
      // router .currentRoute <===> .this.$route
      router.push('/login?return=' + router.currentRoute.path)
    }
    console.dir(error)
    return Promise.reject(error)
  }
)

export default service
